# Definition for a binary tree node.
from math import inf
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        ret = 1000000

        def dfs(node: Optional[TreeNode]):
            nonlocal ret

            if node is None:
                return inf, -inf
            min_l, max_l = dfs(node.left)
            min_r, max_r = dfs(node.right)
            ret = min(abs(max_l - node.val), abs(min_r - node.val), ret)
            return min(min_l, node.val), max(max_r, node.val)

        dfs(root)
        return ret
